package cn.cloud.all.security.web.util.matcher;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import javax.servlet.http.HttpServletRequest;

public class ELRequestMatcher implements RequestMatcher {

    private final Expression expression;

    public ELRequestMatcher(String el) {
        SpelExpressionParser parser = new SpelExpressionParser();
        expression = parser.parseExpression(el);
    }

    public boolean matches(HttpServletRequest request) {
        EvaluationContext context = createELContext(request);
        return expression.getValue(context, Boolean.class);
    }

    /**
     * Subclasses can override this methode if they want to use a different EL root
     * context
     *
     * @return EL root context which is used to evaluate the expression
     */
    public EvaluationContext createELContext(HttpServletRequest request) {
        return new StandardEvaluationContext(new ELRequestMatcherContext(request));
    }

    @Override
    public String toString() {
        return "EL [el=\"" + this.expression.getExpressionString() + "\"" + "]";
    }
}
